# -*- coding: utf-8 -*-
from datetime import datetime

from flask import Blueprint, render_template, request, jsonify

from application import db
from common.libs.render_helper import ops_render
from web.models.food.FoodCat import FoodCat

route_food = Blueprint('food_page', __name__)


@route_food.route("/index")
def index():
    # return render_template("food/index.html")
    return ops_render("food/index.html")


@route_food.route("/info")
def info():
    # return render_template('food/info.html')
    return ops_render("food/info.html")


@route_food.route("/set")
def set():
    # return render_template("food/set.html")
    return ops_render("food/set.html")


@route_food.route("/cat")
def cat():
    # return render_template("food/cat.html")
    context = {}
    cat_list = FoodCat.query.order_by(FoodCat.weight.desc(), FoodCat.id.desc()).all()
    context['cat_list'] = cat_list
    return ops_render("food/cat.html", context)


# 添加美食分类
@route_food.route("/cat-set", methods=['GET', 'POST'])
def catSet():
    # return render_template("food/cat_set.html")
    if request.method == "GET":
        return ops_render('food/cat_set.html')

    if request.method == 'POST':
        resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
        req = request.values
        # 验证前端传过来的信息是否正确
        id = req['id'] if 'id' in req else 0
        name = req['name'] if 'name' in req else ''
        weight = int(req['weight']) if ('weight' in req and int(req['weight']) > 0) else 1
        if name is None or len(name) < 1:
            resp['code'] = -1
            resp['msg'] = "请输入符合规范的分类名称~~"
            return jsonify(resp)
        # 构建美食分类对象
        model_food_cat = FoodCat()
        model_food_cat.name = name
        model_food_cat.weight = weight
        model_food_cat.updated_time = datetime.now()
        model_food_cat.created_time = datetime.now()
        # 提交到数据库
        db.session.add(model_food_cat)
        db.session.commit()
        return jsonify(resp)
